package com.gewu.pm.app;

import androidx.annotation.NonNull;

import com.hjq.base.BaseFragment;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.OnHttpListener;
import com.gewu.pm.action.ToastAction;
import com.gewu.pm.http.model.HttpData;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.Call;

/**
 *  业务 Fragment 基类
 */
public abstract class AppFragment<A extends AppActivity> extends BaseFragment<A>
        implements ToastAction, OnHttpListener<Object> {

    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        A activity = getAttachActivity();
        if (activity != null) {
            return activity.isShowDialog();
        }

        return false;
    }

    /**
     * 显示加载对话框
     */
    public void showDialog() {
        A activity = getAttachActivity();
        if (activity != null) {
            activity.showDialog();
        }
    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        A activity = getAttachActivity();
        if (activity != null) {
            activity.hideDialog();
        }
    }

    /**
     * {@link OnHttpListener}
     */

    @Override
    public void onHttpStart(@NonNull IRequestApi api) {
        showDialog();
    }

    @Override
    public void onHttpSuccess(Object result) {
        if (result instanceof HttpData) {
            toast(((HttpData<?>) result).getMessage());
        }
    }

    @Override
    public void onHttpFail(@NonNull Throwable e) {
        toast(e.getMessage());
    }

    @Override
    public void onHttpEnd(@NonNull IRequestApi api) {
        hideDialog();
    }

    @Override
    public void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //EventBus 默认不注册，子类重写
        if (isRegisteredEventBus()) {
            //注册
            EventBusUtil.register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //EventBus 默认不注册，子类重写
        if (isRegisteredEventBus()) {
            //解注册
            EventBusUtil.unregister(this);
        }
    }

    /**
     * EventBus 事件接收（普通）
     * 可以在子类中重写onEventBusCome()
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(EventBean event) {

    }

    /**
     * EventBus 事件接收（粘性）
     * 可以在子类中重写onStickyEventBusCome()
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(EventBean event) {

    }

    /**
     * 是否注册EventBus
     * 可以在子类中重写isRegisterEventBus()
     */
    protected boolean isRegisteredEventBus() {
        return false;
    }
}